//
//  GradientView.swift
//  Utility
//
//  Created by 于虎拴 on 2022/10/14.
//

import Foundation
import UIKit

public class GradientView: UIView {
  private var gradientLayer: CAGradientLayer {
    guard let gradientLayer = layer as? CAGradientLayer else {
      fatalError("the underlying layer for the button is not CAGradientLayer")
    }
    return gradientLayer
  }
  
  /// default is [CALayer class]. Used when creating the underlying layer for the view.
  public override class var layerClass: AnyClass {
    return CAGradientLayer.self
  }
  
  public var colors: [Any]? = nil {
    didSet{
      gradientLayer.colors = colors
    }
  }
  
  public var locations: [NSNumber]? = nil {
    didSet {
      gradientLayer.locations = locations
    }
  }
  
  public var startPoint: CGPoint = CGPoint(x: 0.5, y: 0) {
    didSet {
      gradientLayer.startPoint = startPoint
    }
  }

  public var endPoint: CGPoint = CGPoint(x: 0.5, y: 1) {
    didSet {
      gradientLayer.endPoint = endPoint
    }
  }
  
  public var type: CAGradientLayerType = .axial {
    didSet {
      gradientLayer.type = type
    }
  }
  
  public override init(frame: CGRect) {
    super.init(frame: frame)
  }
  
  public required init?(coder: NSCoder) {
    super.init(coder: coder)
  }

  
  open class func initWithColors() -> GradientView {
    let view = GradientView()
    let cgColors = [UIColor(red: 0.263, green: 1, blue: 0.733, alpha: 1).cgColor,
                    UIColor(red: 1, green: 0.98, blue: 0.282, alpha: 1).cgColor]
    
    let locations: [CGFloat]? = nil
    let startPoint: CGPoint = .zero
    let endPoint = CGPoint(x: 1, y: 0)
    
    view.colors = cgColors
    view.locations = locations as [NSNumber]?
    view.startPoint = startPoint
    view.endPoint = endPoint
    return view
  }
}
